package com.focusai.efairy.ui.activity.project;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.focusai.efairy.R;
import com.focusai.efairy.model.dev.DevProjectDetailInfo;
import com.focusai.efairy.model.dev.DevType;
import com.focusai.efairy.model.dev.DeviceItem;
import com.focusai.efairy.model.dev.UpLoadDeviceEntity;
import com.focusai.efairy.model.location.Location;
import com.focusai.efairy.model.request.AddDeviceRequest;
import com.focusai.efairy.model.request.GetProjectDevDetailRequest;
import com.focusai.efairy.model.request.PutDeviceRequest;
import com.focusai.efairy.model.response.ProjectManageResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.activity.location.AMapSelectLocationActivity;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.base.SwipeBackBaseActivity;
import com.focusai.efairy.ui.iview.IUpLoadFileListView;
import com.focusai.efairy.ui.presenter.UpLoadFilePresenter;
import com.focusai.efairy.ui.widget.InputGirdImageView;
import com.focusai.efairy.utils.ActivityUtils;
import com.focusai.efairy.utils.Constants;
import com.focusai.efairy.utils.DateUtils;
import com.focusai.efairy.utils.ImageUtils;
import com.focusai.efairy.utils.permission.PermissionListener;
import com.focusai.efairy.utils.permission.PermissionUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPickerActivity;
import me.iwf.photopicker.utils.PhotoPickerIntent;

/**
 * Created by luo_guangwen on 2017/9/12.
 */

public class ProjectAddDeviceActivity extends SwipeBackBaseActivity implements View.OnClickListener {
    public static final String KEY_DEV_ITEM = "key_dev_item";
    public static final String OPENTYPE = "opentype";
    public static final String KEY_PROJECT_ID = "key_project_id";
    public static final String KEY_DEVICE_ID = "key_dev_id";

    private static final int REQUEST_CODE_ADRESS = 0x10;
    private static final int REQUEST_CODE_DEV_TYPE = 0x11;
    private static final int REQUEST_CODE_SCAN = 0x12;
    private static final int REQUEST_CODE_SELECT_ICCID = 0x13;
    private final static int REQUEST_CODE_ALBUM = 100; //打开相册回调
    private final static int REQUEST_CODE_PREVIEW = 101; //打开图片预览
    private final static int EVENT_UPLOAD = 102;
    private final static int EVENT_UPLOAD_FILE_SUCCUSS = 103;
    private final static int EVENT_UPLOAD_FILE_FAIL = 104;
    private EditText editDevName;
    private TextView editProjectAddress;
    private TextView textDevType;
    private TextView textDevMainId;
    private TextView textDevSecondId;
    private EditText editProjectDesc;
    private InputGirdImageView girdImageView;

    //    private ImageView ivScan;
    private boolean isEdit = false;
    private boolean isShowDetail = false;
    private Location location;
    private DevType selectDevType;//所选的设备类型
    private ArrayList<String> options1Items = new ArrayList<>();
    private ArrayList<String> options2Items = new ArrayList<>();
    private ArrayList<String> options3Items = new ArrayList<>();
    private ArrayList<String> fileImageList;

    private String projectId;
    private String deviceId;
    private ProjectManageResponse.DevItem devItem;
    private UpLoadFilePresenter upLoadFilePresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_project_add_dev);
        initView();
        setDefaultValues();
        initPickerData();
        bindEvents();
    }

    @Override
    protected boolean useHandleThread() {
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!isShowDetail) {
            MenuItem menuItem1 = menu.add(MENU_GROUP_ID, MENU_ITEM_ADD, 0, R.string.save).setTitle(R.string.save);
            MenuItemCompat.setShowAsAction(menuItem1, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == MENU_ITEM_ADD) {
            if (verifyInput()) {
                getProcHandler().sendEmptyMessage(EVENT_UPLOAD);
            }
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void initTitte() {
        if (getIntent() != null) {
            isEdit = getIntent().getBooleanExtra(OPENTYPE, false);
            devItem = (ProjectManageResponse.DevItem) getIntent().getSerializableExtra(KEY_DEV_ITEM);
            projectId = getIntent().getStringExtra(KEY_PROJECT_ID);
            deviceId = getIntent().getStringExtra(KEY_DEVICE_ID);
            isShowDetail = getIntent().getBooleanExtra(Constants.KEY_DETAIL, false);
        }
        if (isEdit) {
            setCenterTitleName("编辑设备");
        } else {
            setCenterTitleName("新增设备");
        }
        if (isShowDetail) {
            setCenterTitleName("设备信息");
        }
    }

    @Override
    protected void initView() {
        editDevName = findView(R.id.edit_dev_name);
        textDevType = findView(R.id.text_dev_type);
        textDevMainId = findView(R.id.text_dev_main_id);
        textDevSecondId = findView(R.id.text_dev_second_id);
//        ivScan = findView(R.id.iv_scan);
        editProjectAddress = findView(R.id.text_project_address);
        editProjectDesc = findView(R.id.edit_project_desc);
        girdImageView = findView(R.id.grid_img_view);
        girdImageView.getEditText().setVisibility(View.GONE);
        findView(R.id.ll_project_address).setOnClickListener(this);
        findView(R.id.ll_dev_type).setOnClickListener(this);
        findView(R.id.ll_dev_second_id).setOnClickListener(this);
//        findView(R.id.iv_scan).setOnClickListener(this);
        findView(R.id.ll_dev_main_id).setOnClickListener(this);
    }

    @Override
    protected void bindEvents() {
        girdImageView.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                String path = girdImageView.getItem(holder);
                if (InputGirdImageView.LAST.equals(path)) {
                    openPhotoPickerActivity(girdImageView.DEFAUTECOUNT - fileImageList.size());
                } else {
                    ActivityUtils.openPhotoPagerActivity(ProjectAddDeviceActivity.this, REQUEST_CODE_PREVIEW, girdImageView.getPosition(holder), fileImageList, isEdit || !isShowDetail);
                }
            }
        });
        if (isShowDetail) {
            girdImageView.refreshDataNoAdd(fileImageList);
            if (fileImageList.size() == 0)
                girdImageView.setVisibility(View.GONE);
        } else {
            girdImageView.refreshData(fileImageList);
        }
    }

    @Override
    protected void setDefaultValues() {
        if (devItem != null && devItem.efairydevice_imgurl_list != null) {
            fileImageList = devItem.efairydevice_imgurl_list;
        } else {
            fileImageList = new ArrayList<>();
        }
        upLoadFilePresenter = new UpLoadFilePresenter();
        if (isEdit) {
            initData(devItem);
        } else if (isShowDetail) {
            editProjectDesc.setEnabled(false);
            editDevName.setEnabled(false);
            textDevMainId.setEnabled(false);
            if (!TextUtils.isEmpty(deviceId)) {
                loadProjectDevDetailInfo();
            } else {
                initData(devItem);
            }
        }
    }

    private void initData(ProjectManageResponse.DevItem item) {
        if (item == null)
            return;
        editDevName.setText(item.efairydevice_name);
        editProjectAddress.setText(item.efairydevice_address);
        selectDevType = new DevType(item.efairydevice_belong_system, item.efairydevice_device_type_id
                , DevType.getDevTypeNameById((int) item.efairydevice_belong_system, (int) item.efairydevice_device_type_id));
        textDevType.setText(selectDevType.name);
        editProjectAddress.setText(item.efairydevice_address);
        textDevMainId.setText(DeviceItem.getMainCode(item.efairydevice_uuid));
        textDevSecondId.setText(DeviceItem.getsecodeCode(item.efairydevice_uuid));
        editProjectDesc.setText(item.efairydevice_description);
//        editProjectDesc.setText(item.e);
        location = new Location();
        location.setLatitude(item.efairydevice_location_lat);
        location.setLongitude(item.efairydevice_location_lng);
//        location.set(item.efairyproject_address);
    }

    @Override
    public void onClick(View v) {
        if (isShowDetail)
            return;
        Intent intent;
        switch (v.getId()) {
            case R.id.ll_project_address:
                ActivityUtils.hideInputManager(getContext());
                intent = new Intent(getContext(), AMapSelectLocationActivity.class);
                if (location != null) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(AMapSelectLocationActivity.KEY_SELECT_LOCATION_ITEM, location);
                    intent.putExtras(bundle);
                }
                startActivityForResult(intent, REQUEST_CODE_ADRESS);
                break;
            case R.id.ll_dev_type:
                Intent intent1 = new Intent(getContext(), ProjectSelectDevTypeActivity.class);
                startActivityForResult(intent1, REQUEST_CODE_DEV_TYPE);
                break;
            case R.id.ll_dev_second_id:
                hideSoftInput();
                if (selectDevType == null || TextUtils.isEmpty(textDevType.getText().toString())) {
                    showToast("请先选择设备类型");
                    return;
                }
                if (!DevType.needInputSecondId(selectDevType)) {
                    showToast("所选设备类型不需要选择设备从编码");
                    return;
                }
                showPickerView();
                break;
            case R.id.ll_dev_main_id:
                intent = new Intent(getContext(), ProjectSelectDevIccDActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT_ICCID);
                break;
//            case R.id.iv_scan:
//                intent = new Intent(getContext(), QrCodeCameraPreviewActivity.class);
//                startActivityForResult(intent, REQUEST_CODE_SCAN);
//                break;
            default:
                break;
        }
    }

    private void initPickerData() {
        for (int i = 1; i < 9; i++) {
            options1Items.add(String.valueOf(i));
        }
        for (int i = 1; i < 5; i++) {
            options2Items.add(String.valueOf(i));
        }
        for (int i = 1; i < 256; i++) {
            options3Items.add(String.valueOf(i));
        }
    }

    private void showPickerView() {// 弹出选择器
        int option1 = 0;
        int option2 = 0;
        int option3 = 0;
        if (!TextUtils.isEmpty(textDevSecondId.getText().toString())) {
            String[] strs = textDevSecondId.getText().toString().split("-");
            if (strs != null && strs.length == 3) {
                option1 = options1Items.indexOf(strs[0]);
                option2 = options2Items.indexOf(strs[1]);
                option3 = options3Items.indexOf(strs[2]);
            }
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1) + "-" +
                        options2Items.get(options2) + "-" +
                        options3Items.get(options3);
                textDevSecondId.setText(tx);
                Toast.makeText(ProjectAddDeviceActivity.this, tx, Toast.LENGTH_SHORT).show();
            }
        })
                .setTitleText("选择设备从编码")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setContentTextSize(18)//滚轮文字大小
                .setLinkage(false)//设置是否联动，默认true
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(option1, option2, option3)
                .build();

        pvOptions.setNPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ADRESS:
                    if (data != null && data.getExtras() != null) {
                        location = (Location) data.getExtras().getSerializable(AMapSelectLocationActivity.KEY_SELECT_LOCATION_ITEM);
                        if (location != null) {
                            editProjectAddress.setText(location.getDetailAddress());
                        }
                    }
                    break;
                case REQUEST_CODE_DEV_TYPE:
                    if (data != null && data.getExtras() != null) {
                        selectDevType = (DevType) data.getExtras().getSerializable(ProjectSelectDevTypeActivity.KEY_DEV_TYPE_ITEM);
                        textDevType.setText(selectDevType.name);
                        if (!DevType.needInputSecondId(selectDevType)) {
                            textDevSecondId.setText("1-1-1");
                        }
                    }
                    break;
                case REQUEST_CODE_SCAN:
                    Bundle bundle = data.getExtras();
                    String scanResult = bundle.getString("result");
                    textDevMainId.setText(scanResult);
                    break;
                case REQUEST_CODE_SELECT_ICCID:
                    if (data != null) {
                        textDevMainId.setText(data.getStringExtra(ProjectSelectDevIccDActivity.KEY_CCID));
                    }
                    break;
                case REQUEST_CODE_ALBUM:
                    ArrayList<String> arrayList = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    if (arrayList != null) {
                        fileImageList.addAll(arrayList);
                        girdImageView.refreshData(fileImageList);
                    }
                    break;
                case REQUEST_CODE_PREVIEW:
                    ArrayList<String> arrayList1 = data.getStringArrayListExtra(PhotoPickerActivity.KEY_SELECTED_PHOTOS);
                    if (arrayList1 != null) {
                        fileImageList.clear();
                        fileImageList.addAll(arrayList1);
                        if (isShowDetail) {
                            girdImageView.refreshDataNoAdd(fileImageList);
                        } else {
                            girdImageView.refreshData(fileImageList);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private boolean verifyInput() {
        if (TextUtils.isEmpty(editDevName.getText().toString())) {
            showToast("请填写设备名称");
            return false;
        }
        if (selectDevType == null) {
            showToast("请选择设备类型");
            return false;
        }
//        if (location == null || TextUtils.isEmpty(editProjectAddress.getText().toString())) {
//            showToast("请填写设备地址");
//            return false;
//        }
        if (TextUtils.isEmpty(textDevMainId.getText().toString())) {
            showToast("请填写设备主编码");
            return false;
        }
        if (textDevMainId.getText().toString().length() != 20) {
            showToast("请填写20位设备主编码");
            return false;
        }

        if (TextUtils.isEmpty(textDevSecondId.getText().toString())) {
            showToast("请填写设备从编码");
            return false;
        }
        return true;
    }

    private void addDeviceToProject(List<String> urlList) {

        UpLoadDeviceEntity entity;
        if (isEdit) {
            if (devItem == null)
                return;
            entity = new PutDeviceRequest.UpLoadDeviceEntity();
            ((PutDeviceRequest.UpLoadDeviceEntity) entity).efairydevice_id = devItem.efairydevice_id;
        } else {
            entity = new UpLoadDeviceEntity();
        }
        entity.efairydevice_name = editDevName.getText().toString();
        entity.efairydevice_address = editProjectAddress.getText().toString();
        entity.efairydevice_description = editProjectDesc.getText().toString();
        entity.efairydevice_belong_system = selectDevType.systemId;
        entity.efairydevice_device_type_id = selectDevType.id;
        entity.efairydevice_location_lat = location == null ? 1 : location.getmLatitude();
        entity.efairydevice_location_lng = location == null ? 1 : location.getmLongitude();
        entity.efairydevice_project_id = projectId;
        entity.efairydevice_install_time = DateUtils.getCurrentDateYMDHSS();
        entity.efairydevice_imgurl_list = urlList;
        entity.efairydevice_uuid = textDevMainId.getText().toString().trim() + DeviceItem.bytes2HexString(textDevSecondId.getText().toString().trim());
        showSingleDialog("正在保存数据..");
        Response.Listener<String> listener = new Response.Listener<String>() {
            @Override
            protected void onSuccess(String response) {
                closeSingleDialog();
                if (!ProjectAddDeviceActivity.this.isFinishing()) {
                    if (isEdit) {
                        showToast("设备修改成功");
                    } else {
                        showToast("添加设备成功");
                    }
                    setResult(RESULT_OK);
                    finish();
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                doException(exception);
            }
        };
        if (isEdit) {
            HttpManager.getInstance().sendRequest(new PutDeviceRequest((PutDeviceRequest.UpLoadDeviceEntity) entity, listener));
        } else {
            HttpManager.getInstance().sendRequest(new AddDeviceRequest(entity, listener));
        }
    }

    private void loadProjectDevDetailInfo() {
        showSingleDialog("正在加载设备信息..");
        HttpManager.getInstance().sendRequest(new GetProjectDevDetailRequest(projectId, deviceId, new Response.Listener<DevProjectDetailInfo>() {
            @Override
            protected void onSuccess(DevProjectDetailInfo response) {
                closeSingleDialog();
                if (response != null) {
                    response.efairydevice_belong_system = 10;
                    initData(response);
                }
            }

            @Override
            protected void onFail(NetworkException exception) {
                closeSingleDialog();
                doException(exception);
            }
        }));
    }

    /**
     * 打开相册
     */
    private void openPhotoPickerActivity(final int count) {
        checkPermission(PermissionUtil.PERMISSION_STORAGE, new PermissionListener() {
            @Override
            public void onSucceed(int requestCode, List<String> grantedList) {
                PhotoPickerIntent intent = new PhotoPickerIntent(getContext());
                intent.setPhotoCount(count);
                intent.setShowCamera(false);
                startActivityForResult(intent, REQUEST_CODE_ALBUM);
            }

            @Override
            public void onFailed(int requestCode, List<String> deniedList) {
                showToast("应用没读SD卡权限");
            }
        }, Manifest.permission.READ_EXTERNAL_STORAGE);

    }

    @Override
    protected boolean procHandlerCallback(Message msg) {
        switch (msg.what) {
            case EVENT_UPLOAD:
                upLoadFile(fileImageList);
                break;
            default:
                break;
        }
        return super.procHandlerCallback(msg);
    }

    @Override
    protected boolean uiHandlerCallback(Message msg) {
        switch (msg.what) {
            case EVENT_UPLOAD_FILE_SUCCUSS:
                addDeviceToProject((List<String>) msg.obj);
                break;
            case EVENT_UPLOAD_FILE_FAIL:
                closeSingleDialog();
                showToast("上传图片失败");
                break;
            default:
                break;
        }
        return super.uiHandlerCallback(msg);
    }

    private void sendUploadFileSuccess(List list) {
        Message msg = getUiHandler().obtainMessage();
        msg.what = EVENT_UPLOAD_FILE_SUCCUSS;
        msg.obj = list == null ? new ArrayList<>() : list;
        getUiHandler().sendMessage(msg);
    }

    private void upLoadFile(List<String> fileOldPath) {
        showSingleDialog("正在上传数据..");
        if (fileOldPath == null || fileOldPath.size() == 0) {
            sendUploadFileSuccess(null);
            return;
        }
        List<String> newImagePaths = new ArrayList<>();
        final List<String> urlImagePaths = new ArrayList<>();
        for (String oldPath : fileOldPath) {
            if (oldPath.startsWith("http")) {
                urlImagePaths.add(oldPath);
            }
            String compressImageFile = ImageUtils.saveCompressImageFile(oldPath);
            if (!TextUtils.isEmpty(compressImageFile)) {
                newImagePaths.add(compressImageFile);
            }
        }
        if (newImagePaths.size() == 0)
            sendUploadFileSuccess(urlImagePaths);
        upLoadFilePresenter.upLaodFiles(newImagePaths, 0, new IUpLoadFileListView() {
            @Override
            public void onUpLoadFileSeccuss(LinkedHashMap<String, String> urlMap) {
                Iterator it = urlMap.entrySet().iterator();
                List<String> urlList = new ArrayList<>();
                while (it.hasNext()) {
                    urlList.add((String) ((Map.Entry) it.next()).getKey());
                }
                urlImagePaths.addAll(urlList);
                Message msg = getUiHandler().obtainMessage();
                msg.what = EVENT_UPLOAD_FILE_SUCCUSS;
                msg.obj = urlImagePaths;
                getUiHandler().sendMessage(msg);
            }

            @Override
            public void onUpLoadFileFail(String errormsg) {
                getUiHandler().sendEmptyMessage(EVENT_UPLOAD_FILE_FAIL);
            }

            @Override
            public void onUpLoaditemSussuss(String url, int position, int count) {
                showSingleDialog("正在上传图片" + position + "/" + count);
            }
        });
    }


}
